package io.renren.modules.app.controller;

/**
 * ClassName: ZFBController
 * Author:   WGG
 * Date:    2022-12-2022/12/16-10:02
 * Version: 1.0
 * Description:
 */
import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.AlipayUtils;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.wxpay.config.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.entity.OrderEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.*;
import io.renren.modules.app.service.OrderService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app/zfb")
@Api("支付宝业务接口")
public class ZFBController {

    @Value("${alipay.app.app-id}")
    private String app_appId;

    @Value("${alipay.app.public-key}")
    private String app_publicKey;

    @Value("${alipay.app.private-key}")
    private String app_privateKey;

    @Value("${alipay.gateway}")
    private String gateway;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtUtils jwtUtils;

    @Login
    @PostMapping("/nativePayOrder")
    @ApiOperation("native付款")
    public R nativePayOrder(@RequestBody PayOrderForm form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = form.getOrderId();
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        QueryWrapper wrapper = new QueryWrapper(user);
        long count = userService.count(wrapper);
        if (count == 0) {
            return R.error("用户不存在");
        }
        OrderEntity order = new OrderEntity();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        wrapper = new QueryWrapper(order);
        count = orderService.count(wrapper);
        if (count == 0) {
            return R.error("无效订单");
        }
        order = new OrderEntity();
        order.setId(orderId);
        wrapper = new QueryWrapper(order);
        order = orderService.getOne(wrapper);
        //向支付宝平台发出请求，创建支付订单
        String amount = order.getAmount()+"";
        try {
            //调用支付宝的支付sdk
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                    app_publicKey,
                    "RSA2"
            );
            //设置支付请求的相关信息
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //设置返回的页面
            request.setReturnUrl("http://127.0.0.1:5500/mall/order.html");
            request.setNotifyUrl("http://www.demo.com");
            String subject = "Native付款";
            String body = "测试Native付款";
            request.setBizContent("{\"out_trade_no\":\"" + order.getCode() + "\","
                    + "\"total_amount\":\"" + amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //发送创建支付订单的请求
            AlipayTradePagePayResponse response = client.pageExecute(request);
            System.out.println(response);
            //会响应支付的结果
            String htmlCode = response.getBody();
            System.out.println(htmlCode);
            //如果响应中的属性是Success说明支付成功
            if (response.isSuccess()) {
                //修改订单
                order.setPaymentType(2); //支付方式  1.微信   2.支付宝   3.银联
                order.setStatus(2); //设置支付订单的状态
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", order.getId());
                orderService.update(order, updateWrapper);
                return R.ok().put("htmlCode", htmlCode);
            }else {
                return R.error("支付订单创建失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("支付宝支付模块故障");
        }
    }


    @Login
    @PostMapping("/updateNativeOrderStatus")
    @ApiOperation("更新商品订单状态")
    public R updateNativeOrderStatus(@RequestBody UpdateNativeOrderStatusForm form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        int userId = Integer.parseInt(jwtUtils.getClaimByToken(token).getSubject());
        String code = form.getCode();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        orderEntity.setCode(code);
        QueryWrapper wrapper = new QueryWrapper(orderEntity);
        int count = orderService.count(wrapper);
        if (count == 0) {
            return R.error("用户与订单不匹配");
        }
        try {
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                    app_publicKey,
                    "RSA2"
            );
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + code + "\"," +
                    "    \"query_options\":[" +
                    "    \"TRADE_SETTLE_INFO\"" +
                    "    ]" +
                    "  }");
            AlipayTradeQueryResponse response = client.execute(request);
            if (response.isSuccess()) {
                String tradeState = response.getTradeStatus();
                if ("TRADE_SUCCESS".equals(tradeState) || "TRADE_FINISHED".equals(tradeState)){
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("code",code);
                    updateWrapper.set("status",2);
                    updateWrapper.set("payment_type",2);
                    updateWrapper.set("prepay_id", response.getTradeNo());
                    orderService.update(updateWrapper);
                    return R.ok("订单状态已修改");
                }else {
                    return R.ok("订单状态未修改");
                }
            }
            return R.ok("订单状态未修改");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("查询支付订单失败");
        }
    }

    @Login
    @PostMapping("/scanCodePayOrder")
    @ApiOperation("付款码收款")
    public R scanCodePayOrder(@RequestBody ScanCodePayOrderForm form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = form.getOrderId();
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        QueryWrapper wrapper = new QueryWrapper(user);
        long count = userService.count(wrapper);
        if (count == 0) {
            return R.error("用户不存在");
        }
        OrderEntity order = new OrderEntity();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        wrapper = new QueryWrapper(order);
        count = orderService.count(wrapper);
        if (count == 0) {
            return R.error("无效订单");
        }

        order = new OrderEntity();
        order.setId(orderId);
        wrapper = new QueryWrapper(order);
        order = orderService.getOne(wrapper);
        //向支付宝平台发出请求，创建支付订单
        String amount = order.getAmount()+"";
        try {
            //调用支付宝的支付sdk
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                    app_publicKey,
                    "RSA2"
            );
            //设置支付请求的相关信息
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + order.getCode() + "\"," +
                    "    \"scene\":\"bar_code\"," +
                    "    \"auth_code\":\"" + form.getAuthCode() + "\"," +
                    "    \"subject\":\"扫码付款测试\"," +
                    "    \"store_id\":\"NJ_001\"," +
                    "    \"timeout_express\":\"2m\"," +
                    "    \"total_amount\":\"" + amount + "\"" +
                    "  }");
            //发送创建支付订单的请求
            AlipayTradePayResponse response = client.execute(request);
            //如果响应中的属性是Success说明支付成功
            if (response.isSuccess()&& response.getCode().equals("10000")) {
                String prepayId = response.getTradeNo();
                //修改订单
                order.setPaymentType(2); //支付方式  1.微信   2.支付宝   3.银联
                order.setStatus(2); //设置支付订单的状态
                order.setPrepayId(prepayId);
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", order.getId());
                orderService.update(order, updateWrapper);
                return R.ok("付款成功");
            }else {
                return R.error("付款失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("支付宝支付模块故障");
        }
    }



}
